<template>
  <form-wrap :rules="rules" :schema="formSchema" @register="formRegister" />
</template>
<script setup lang="ts">
  import { listValidTreeNodeApi as listOrgTreeNodeApi } from '@/api/system/organization';
  import { listAllApi as listRoleApi } from '@/api/system/role';
  import { useForm } from '@/hooks/form';
  import { useValidator } from '@/hooks/validator';

  const { required, lengthRange, checkMobile, checkUsername, checkEmail } =
    useValidator();

  const formSchema = ref<FormSchema[]>([
    {
      field: 'username',
      label: '用户名',
      type: 'Input',
      props: {
        maxlength: 30,
      },
    },
    {
      field: 'password',
      label: '密码',
      type: 'a-input-password',
      props: {
        maxlength: 30,
      },
    },
    {
      field: 'repassword',
      label: '确认密码',
      type: 'a-input-password',
      props: {
        maxlength: 30,
      },
    },
    {
      field: 'realName',
      label: '真实姓名',
      type: 'Input',
      props: { maxlength: 30 },
    },
    {
      field: 'gender',
      label: '性别',
      type: 'Select',
      enumName: 'Gender',
    },
    {
      field: 'mobile',
      label: '移动电话',
      type: 'Input',
      props: {
        maxlength: 11,
      },
    },
    {
      field: 'email',
      label: '电子邮件',
      type: 'Input',
      props: {
        maxlength: 100,
      },
    },
    {
      field: 'orgId',
      label: '所属组织',
      type: 'a-tree-select',
      props: {
        fieldNames: {
          key: 'id',
          title: 'name',
        },
      },
      optionApi() {
        return listOrgTreeNodeApi();
      },
      optionTo: 'props.data',
    },
    {
      field: 'state',
      label: '启用状态',
      type: 'Select',
      enumName: 'State',
    },
    {
      field: 'roles',
      label: '角色',
      type: 'Select',
      props: {
        multiple: true,
        fieldNames: {
          label: 'name',
          value: 'id',
        },
      },
      optionApi() {
        return listRoleApi();
      },
    },
  ]);

  const rules = reactive({
    username: [required(), checkUsername()],
    password: [required(), lengthRange({ min: 6, max: 30 })],
    repassword: [
      required(),
      lengthRange({ min: 6, max: 30 }),
      {
        validator(val: string, callback: (error?: string) => void) {
          const password = getValue('password');
          if (val !== password) {
            callback('密码不一致');
          } else {
            callback();
          }
        },
      },
    ],
    realName: [required()],
    gender: [required()],
    mobile: [checkMobile()],
    email: [checkEmail()],
    orgId: [required()],
    state: [required()],
  });

  const { formRegister, formMethods } = useForm();
  const { submitForm, getValue } = formMethods;
  const submit = async () => {
    return await submitForm();
  };
  defineExpose({
    submit,
  });
</script>
